package com.k.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Security;
import java.util.List;

/**
 * @program: SpringSecote01
 * @ClassName ToController
 * @description:
 * @author: xiaoJie
 * @create: 2024-09-11 20:27
 * @Version 1.0
 */
@Controller
public class ToController {

    @RequestMapping("/{path}")
    public String path(@PathVariable("path") String path){
        if (path.equals("favicon.ico")){
            System.out.println("重生之我在中央当政委 ");
            return "/login";
        }
        //获取SecuritySession
//        SecurityContext context = SecurityContextHolder.getContext();
//        Authentication authentication = context.getAuthentication();
//        User principal = (User) authentication.getPrincipal();
//        String username = principal.getUsername();

        return path;
    }


    @Autowired
    private SessionRegistry sessionRegistry;
    //踢人下线
    @RequestMapping("/tiren")
    public void tiren(String name){

        List<Object> allPrincipals = sessionRegistry.getAllPrincipals();//获取所有用户
        if (allPrincipals.size() > 0){
            allPrincipals.forEach(o->{
                if (o instanceof User){
                    User user = (User) o;
                    if(user.getUsername().equals(name)){
                        List<SessionInformation> allSessions = sessionRegistry.getAllSessions(user, false);
                        if (allSessions.size() > 0 && allSessions != null){
                            allSessions.forEach(session->{
                                session.expireNow();//如果session还在则直接清理
                            });
                        }
                    }
                }
            });
        }

    }


}
